package com.xing.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day38web2
 * 2021/4/28 14:49
 */
public class DataSourceUtils {
    private static DruidDataSource dataSource=null;

    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
    static {
        try {
            Properties properties = new Properties();
            InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(is);
            is.close();
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            System.out.println("初始化连接池失败...");
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }

    //如果处理事务
    public static Connection  getConnection(){
       Connection connection=threadLocal.get();
        try {
            if(connection==null){
                 connection = dataSource.getConnection();
                 threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static void begin() throws SQLException {
        Connection connection=getConnection();
        if(connection!=null){
            connection.setAutoCommit(false);

        }
    }
    public static void commit() throws SQLException {
        Connection connection=getConnection();
        if(connection!=null){
            connection.commit();
        }
    }
    public static void rollback() throws SQLException {
        Connection connection=getConnection();
        if(connection!=null){
            connection.rollback();

        }
    }
    public static void close() throws SQLException {
        Connection connection=getConnection();
        if(connection!=null){
            connection.close();
            threadLocal.remove();
        }
    }

    public static  void closeAll(ResultSet rs, Statement stat,Connection conn){
        try {
            if(rs!=null){
                rs.close();
            }
            if(stat!=null){
                stat.close();
            }
            if(conn!=null){
                if(conn.getAutoCommit()){
                    conn.close();
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }













}
